<template>
  <div class="app-container">
    <el-card class="mar_bottom">
      <el-search-form label-width="90px" @search="onSearch" @reset="onReset">
        <el-form-item>
          <el-select
            size="small"
            style="width: 100px; margin-right: -2px"
            v-model="timeType"
            placeholder="请选择"
          >
            <el-option label="创建时间" value="createDate"></el-option>
            <el-option label="订单时间" value="orderTime"></el-option>
          </el-select>
          <el-date-picker
            size="small"
            v-model="searchBody.timeRange"
            style="width: 350px"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="城市">
          <el-cascader
            v-model="regionIdList"
            size="small"
            :options="regionTree"
            :props="{
              label: 'name',
              value: 'id',
              checkStrictly: true,
            }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="订单ID">
          <el-input
            clearable
            size="small"
            v-model="searchBody.id"
            class="el-input__small"
          ></el-input>
        </el-form-item>
        <el-form-item label="业主手机号">
          <el-input
            clearable
            size="small"
            v-model="searchBody.phone"
            class="el-input__small"
          ></el-input>
        </el-form-item>
        <el-form-item label="注册人账号">
          <el-input
            clearable
            size="small"
            v-model="searchBody.userPhone"
            class="el-input__small"
          ></el-input>
        </el-form-item>
        <el-form-item label="注册人上级号">
          <el-input
            clearable
            size="small"
            v-model="searchBody.pUserPhone"
            class="el-input__small"
          ></el-input>
        </el-form-item>
        <el-form-item label="审核日期">
          <el-date-picker
            v-model="searchBody.audiDate"
            type="date"
            placeholder="选择日期"
            @change="handleChangeAudiDate"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="searchBody.zhuangtai" placeholder="请选择">
            <el-option label="出单" value="1"></el-option>
            <el-option label="已量房" value="3"></el-option>
            <el-option label="已签单" value="5"></el-option>
            <el-option label="跑单" value="2"></el-option>
            <el-option label="无效" value="4"></el-option>
          </el-select>
        </el-form-item>
      </el-search-form>
      <el-button type="primary" size="small" @click="handleClick('exportOut')"                 v-if="isShowExportOutData"
      >导出数据</el-button
      >
    </el-card>

    <el-card>
      <div>订单总金额 : {{ totalOrderPrice }}</div>
      <el-tabs
        style="margin-top: 15px"
        v-model="searchBody.audiStatus"
        @tab-click="getData"
      >
        <el-tab-pane label="全部" name="0"></el-tab-pane>
        <el-tab-pane label="待审核" name="1"></el-tab-pane>
        <el-tab-pane label="有效" name="5"></el-tab-pane>
        <el-tab-pane label="已量房" name="21"></el-tab-pane>
        <el-tab-pane label="未量房" name="20"></el-tab-pane>
      </el-tabs>

      <el-pagination
        small
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="pageSizeOpts"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      >
      </el-pagination>
      <div class="have-pagination-container">
        <el-table v-loading="loading.list" :data="list">
          <el-table-column
            label="线索ID"
            prop="id"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="创建时间"
            prop="createDate"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="业主"
            prop="name"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="手机"
            prop="phone"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="城市"
            prop="cityValue"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="地址"
            prop="address"
            align="center"
            width="360"
          ></el-table-column>
          <el-table-column
            label="状态"
            prop="zhuangtaiValue"
            align="center"
            width="50"
          ></el-table-column>
          <el-table-column
            label="面积"
            prop="mianji"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="喜欢风格"
            prop="xihuanfenggeValue"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="订单价格"
            prop="orderPrice"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="剩余可抢单数"
            prop="resideCanBuyZxCount"
            align="center"
            width="80"
          >
          </el-table-column>
          <el-table-column
            label="审核时间"
            prop="audiDate"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="量房照片"
            prop="liangfangImage"
            align="center"
            width="100"
          >
            <template slot-scope="scope">
              <el-image
                style="width: 30px; height: 30px"
                :src="scope.row.liangfangImage"
                :preview-src-list="[scope.row.liangfangImage]"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            fixed="right"
            label="操作"
            width="160"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="handleClick('xiangqing', scope.row)"
                >详情</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="handleClick('liangfang', scope.row)"
                :disabled="scope.row.isLiangfang === '1'"
                >已量房</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="handleClick('cancelLiangfang', scope.row)"
                :disabled="scope.row.isLiangfang === '0'"
                v-if="isShowCancelLiangfang"
              >取消量房</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        small
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="pageSizeOpts"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      >
      </el-pagination>
    </el-card>

    <!-- 查看详情信息 -->
    <XiangDia ref="xiaDiaRef" @closeDiaFun="closeXiaDia"></XiangDia>



  </div>
</template>

<script>
import {
  paidanOrder,
  selectPaidanPageVo,
  selectRegionTree,
  exportInData,
  selectJiaZhuangOrderPage,
  jiazhuangdingdanshenhe,
  selectTotalOrderPrice,
  exportJiazhuangOrderList,
  houtaiSetLiangfang,
  selectJiaOrderDetailVo,
  jiaOrderCancelLiangfang,
} from "@/api/api.js";
import { sysDict_delete } from "@/api/dataDict";
import { downloadFile } from "@/utils/index";
import XiangDia from "./xiangDia.vue";
import { getApiUrlList } from '@/utils/auth'

const getDefaultForm = () => ({
  name: null,
  sex: null,
  phone: null,
  addrCode: null,
  address: null,
  mianji: null,
  resouces: null,
  remark: null,
  logs: null,
  marketingType: null,
});
const getDefaultSearchBody = () => ({
  timeRange: null,
  resource: null,
  phone: null,
  yezhu: null,
  orderNo: null,
  userIdList: null,
  id: null,
  audiStatus: "0",
  audiDate: null,
  isLiangfang: null,
  pUserPhone: null,
  userPhone: null,
  xiansuoStatus: null,
  zhuangtai:null,
});
export default {
  components: {
    XiangDia,
  },
  data() {
    return {
      isShowCancelLiangfang:false,
      isShowExportOutData:false,
      isShow:false,
      regionTree: [],
      shenheLoading: false,
      regionIdList:null,
      timeType: "createDate",
      searchType: "phone",
      dialogTitle: "",
      dialogTitle2: "",
      dialogTitle3: "",
      handleType: "",
      pageNo: 1,
      pageSize: 20,
      totalCount: 0,
      pageSizeOpts: [20, 50, 100, 300, 500],
      loading: {
        list: false,
        list2: false,
      },
      list: [],
      paidanData: {},
      selectRow: [], // 选中行
      lookDialog: false,
      editDialog: false, // 查看详情弹窗
      updateForm: getDefaultForm(),
      searchBody: getDefaultSearchBody(),
      totalOrderPrice: 0,

      xiangData: {
        name: null,
      },
    };
  },
  created() {
    this.getData();
    var apiUrlList = getApiUrlList();
    if(apiUrlList.includes("/dailiOrder/post/jiaOrderCancelLiangfang")){
      this.isShowCancelLiangfang=true;
    };
    if(apiUrlList.includes("/dailiOrder/post/exportJiazhuangOrderList")){
      this.isShowExportOutData=true;
    };
  },
  methods: {
    handleChangeAudiDate() {
      // 假设我们要转换到东八区（北京时间）
      const timezoneOffset = new Date().getTimezoneOffset();
      const offset = 8 * 60 - timezoneOffset; // 东八区比UTC偏前8小时
      const date = new Date(
        this.searchBody.audiDate.getTime() + offset * 60000
      );
      this.searchBody.audiDate = date;
      // 现在 date 是东八区的时间
      console.log("东八区时间:", date);
    },
    onSearchTypeChange(key) {
      let val;
      for (let key2 of ["yezhu", "phone", "orderNo", "id"]) {
        val = this.searchBody[key2] || val;
      }
      this.searchBody = Object.assign(this.searchBody, {
        [key]: val,
      });
    },
    getData() {
      this.loading.list = true;
      const { timeRange, userIdList, ...rest } = this.searchBody;
      const [startTime, endTime] = timeRange || [null, null];
      /*const _userIdList = (userIdList || []).reduce((a, b) => {
        return Array.from(new Set(a.concat(b)));
      }, []);*/
      var regionId = null;
      if (this.regionIdList != null) {
        var length = this.regionIdList.length;
        regionId = this.regionIdList[length - 1];
      }
      selectJiaZhuangOrderPage({
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        startTime: startTime,
        endTime: endTime,
        regionId: regionId,
        ...rest,
      }).then(({ result }) => {
        this.list = result?.data || [];
        this.totalCount = result?.totalCount || "-";
        this.loading.list = false;
      });
      selectRegionTree().then(({ result }) => {
        this.regionTree = result || [];
      });
      selectTotalOrderPrice({
        startTime: startTime,
        endTime: endTime,
        regionId: regionId,
        ...rest,
      }).then(({ result }) => {
        this.totalOrderPrice = result.orderPrice;
      });
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getData();
    },
    handleSelectionChange(val) {
      this.selectIds = val.map((d) => d.id);
    },
    onSearch() {
      this.pageNo = 1;
      this.getData();
    },
    onReset() {
      this.pageNo = 1;
      this.searchBody = getDefaultSearchBody();
      this.getData();
    },

    handleClick(type, row, title) {
      this.handleType = type;
      switch (type) {
        case "xiangqing":
          selectJiaOrderDetailVo({
            id: row.id,
          }).then((res) => {
            this.xiangData = res.result;
            this.$refs.xiaDiaRef.openDia(this.xiangData);
          });
          break;
        case "liangfang":
          this.$confirm(`确认已量房？`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            houtaiSetLiangfang({
              id: row.id,
            }).then((res) => {
              this.$message.success(res.msg || "操作成功");
              this.getData();
            });
          });
          break;
        case "cancelLiangfang":
          this.$confirm(`确认取消量房？`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            jiaOrderCancelLiangfang({
              id: row.id,
            }).then((res) => {
              this.$message.success(res.msg || "操作成功");
              this.getData();
            });
          });
          break;
        case "exportOut":
          const { timeRange, userIdList, ...rest } = this.searchBody;
          const [startTime, endTime] = timeRange || [null, null];
          exportJiazhuangOrderList({
            startTime: startTime,
            endTime: endTime,
            phone: this.searchBody.phone,
            audiDateStr: this.searchBody.audiDate,
            audiStatus: this.searchBody.audiStatus,
          }).then((res) => {
            let fileName = res.headers["content-disposition"].replaceAll(
              /.*?filename=(.*?)/g,
              "$1"
            );
            downloadFile(res.data, decodeURI(fileName), "blob");
            this.$message.success("导出成功");
          });
          break;


        default:
          return;
      }
    },

    closeXiaDia(val) {
      this.getData();
    },





  },
};
</script>

<style scoped>

</style>
